package com.embhealth.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.embhealth.constant.RedisConstant;
import com.embhealth.dao.AddressDao;
import com.embhealth.entity.LogException.DeleteAddressException;
import com.embhealth.entity.PageResult;
import com.embhealth.entity.QueryPageBean;
import com.embhealth.pojo.Address;
import com.embhealth.pojo.CheckItem;
import com.embhealth.service.AddressService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 体检机构服务
 */
@Service(interfaceClass = AddressService.class)
public class AddressServiceImpl implements AddressService {
    
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 体检机构地址信息分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //完成分页查询基于mybatis框架的PageHelper分页助手
        PageHelper.startPage(currentPage,pageSize);
        Page<Address> page = addressDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Address> result = page.getResult();
        return new PageResult(total,result);
    }

    /**
     * 新增体检机构地址信息
     * @param address
     */
    @Override
    public void add(Address address) {
        addressDao.add(address);
        //将图片名称保存到Redis中
        String fileName = address.getImg();
        if (fileName!=null) {
          jedisPool.getResource().sadd(RedisConstant.Address_PIC_DB_RESOURCES,fileName);
        }
        
    }

    /**
     * 编辑体检机构地址信息回显
     * @param id
     * @return
     */
    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    /**
     * 删除体检机构地址信息
     * @param id
     */
    @Override
    public void delete(Integer id) throws Exception{
        //根据体检机构id 查询相关联的订单表信息
        long count = addressDao.findAssociationByAddressId(id);
        if (count>0) {
            throw new DeleteAddressException();
        }
        //删除本表数据
        addressDao.deleteById(id);
    }

    /**
     * 编辑体检机构地址信息
     * @param address
     */
    @Override
    public void edit(Address address) {
        //操作检查机构表,编辑检查机构地址信息
        addressDao.edit(address);
        String fileName = address.getImg();
        //将上传的图片名称存到redis,基于redis的set集合存储
        jedisPool.getResource().sadd(RedisConstant.Address_PIC_DB_RESOURCES, fileName);
    }

    /**
     * 查询所有的体检机构地址信息
     * @return
     */
    @Override
    public List<Address> findAllAddress() {
        return addressDao.findAllAddress();
    }
}
